package com.corecmd.tcloud.tcimserver.im.handler;

import com.corecmd.tcloud.tcimcommon.im.common.PacketCodeC;
import com.corecmd.tcloud.tcimcommon.im.domain.LoginRequestPacket;
import com.corecmd.tcloud.tcimcommon.im.domain.LoginResponsePacket;
import com.corecmd.tcloud.tcimcommon.im.domain.MessageRequestPacket;
import com.corecmd.tcloud.tcimserver.cache.ImCacheManager;
import com.corecmd.tcloud.tcimserver.domain.UserInfoDTO;
import com.corecmd.tcloud.tcimserver.enums.ImClientPlatform;
import com.corecmd.tcloud.tcimserver.im.common.ImSessionHolder;
import com.corecmd.tcloud.tcimserver.service.IUserService;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

/**
 * @author : TianShaoJiao
 * @date : 2021/2/20
 * @description :
 **/
@Slf4j
@Scope("prototype")
@Component
public class LoginRequestHandler extends SimpleChannelInboundHandler<LoginRequestPacket> {
    @Autowired
    private ImCacheManager imCacheManager;
    @Value("${imserver.host}")
    private String imServerHost;
    @Value("${imserver.port}")
    private int imServerPort;
    @Value("${imserver.protocol}")
    private String imServerProtocol;
    @Value("${server.port}")
    private int imServerHttpPort;
    @Value("${imserver.clientKeyPrefix}")
    private String imClientServerPrefix;
    @Autowired
    private IUserService userService;
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, LoginRequestPacket loginRequestPacket) throws Exception {
        String userId = loginRequestPacket.getUserId();
        String loginPlatform = loginRequestPacket.getPlatform();
        ImClientPlatform platform = ImClientPlatform.match(loginPlatform);
        log.info("用户："+userId+"登录");
        Channel channel = channelHandlerContext.channel();
        if (null != platform){
            UserInfoDTO userInfoDTO = userService.getUser(Integer.parseInt(userId));
            if (userInfoDTO != null){
                //登陆成功后，给channel设置特有属性
                AttributeKey<String> userIdKey = AttributeKey.valueOf("userId");
                channel.attr(userIdKey).set(userId);
                AttributeKey<String> userNameKey = AttributeKey.valueOf("userName");
                channel.attr(userNameKey).set(userInfoDTO.getUserName());
                ImSessionHolder.put(userId,(NioSocketChannel) channel);
                //向缓存中写入用户与im服务器的绑定信息
                imCacheManager.setKeyValue(imClientServerPrefix + userId + "_" + platform.getPlatform_name_en(), imServerHost + ":" + imServerPort + ":" + imServerHttpPort + ":" + imServerProtocol);
                //发送登陆响应
                LoginResponsePacket loginResponsePacket = new LoginResponsePacket();
                loginResponsePacket.setStatusCode(200);
                loginResponsePacket.setMessage("登录成功");
                // 编码
                ByteBuf buffer = new PacketCodeC().encode(loginResponsePacket);
                // 写数据
                channel.writeAndFlush(buffer);
                //广播上线通知
                MessageRequestPacket messageRequestPacket = new MessageRequestPacket();
                messageRequestPacket.setMsgContent("用户:"+userInfoDTO.getUserName()+"上线了！！！");
                ImSessionHolder.broadcastMessage(messageRequestPacket,userId);
                channelHandlerContext.flush();
            } else {
                //发送登陆响应
                LoginResponsePacket loginResponsePacket2 = new LoginResponsePacket();
                loginResponsePacket2.setStatusCode(0);
                loginResponsePacket2.setMessage("用户："+userId+"不存在");
                // 编码
                ByteBuf buffer2 = new PacketCodeC().encode(loginResponsePacket2);
                // 写数据
                channel.writeAndFlush(buffer2);
                channelHandlerContext.close();
            }
        } else {
            //发送登陆响应
            LoginResponsePacket loginResponsePacket3 = new LoginResponsePacket();
            loginResponsePacket3.setStatusCode(0);
            loginResponsePacket3.setMessage("客户端类型："+loginPlatform+"不支持");
            // 编码
            ByteBuf buffer3 = new PacketCodeC().encode(loginResponsePacket3);
            // 写数据
            channel.writeAndFlush(buffer3);
            channelHandlerContext.close();
        }

    }
}
